package com.gitee.wsl.compose.chart.animation

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.AnimationVector1D
import androidx.compose.animation.core.tween
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

sealed class AnimationMode {
    data class Together(val delayBuilder: (index: Int) -> Long = { 0 }) : AnimationMode()
    data object OneByOne : AnimationMode()
}

/**
 * RC means Row & Column
 */
@Composable
fun <Data> ImplementRCAnimation(
    data:List<Data>,
    animationMode: AnimationMode = AnimationMode.OneByOne,
    spec: (Data)->AnimationSpec<Float> = { tween(500) },
    delay:Long = 0L,
    before:()->Unit = {},
    animator:(Int,data:Data) -> Animatable<Float, AnimationVector1D>
) {
    LaunchedEffect(data) {
        before()
        delay(delay)
        data.forEachIndexed { index, data ->
            val animate: suspend () -> Unit = {
                animator(index,data).animateTo(
                    1f,
                    animationSpec = spec(data)
                )
            }
            when (animationMode) {
                is AnimationMode.OneByOne -> {
                    animate()
                }

                is AnimationMode.Together -> {
                    launch {
                        delay(animationMode.delayBuilder(index))
                        animate()
                    }
                }
            }
        }
    }
}